/*
 * @Descripttion: 实现ref、forwardRef
 * @Author: lukasavage
 * @Date: 2021-11-10 21:48:58
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-12-30 21:22:06
 */
import { Component } from './component2';
import { REACT_ELEMENT, REACT_FORWARD_REF } from './constants';
import { wrapToVDOM } from './utils';

function createElement(type, config, children) {
  let key = null,
    ref = null; 
  if (config) {
    key = config.key;
    ref = config.ref;
    delete config.ref; 
    delete config.key;
    delete config.__source;
    delete config.__self;
  }
  const props = { ...config };
  if (arguments.length > 3) {
    props.children = Array.prototype.slice.call(arguments, 2).map(wrapToVDOM);
  } else if (arguments.length === 3) {
    props.children = wrapToVDOM(children);
  }

  return {
    $$typeof: REACT_ELEMENT,
    key,
    ref,
    type,
    props,
  };
}

function createRef() {
  // 在react-dom的createDOM中，将真是DOM赋值给当前的current即可实现
  return { current: null };
}

function forwardRef(render) {
  return {
    $$typeof: REACT_FORWARD_REF,
    render,
  };
}

const react = {
  createElement,
  Component,
  createRef,
  forwardRef
};

export default react;
